package com.dating.activity;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

import com.dating.entities.Her;
import com.dating.entities.Me;
import com.dating.entities.UserItemizedOverlay;
import com.dating.libs.web.services.datingservice.AroundUser;
import com.dating.libs.web.services.datingservice.BasicInformation;
import com.dating.libs.web.services.datingservice.DatingService;
import com.dating.pref.Constant;
import com.dating.pref.Function;
import com.dating.pref.Pref;
import com.dating.view.DtOverlay;
import com.dating.view.MapUserAdapter;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class ArroundMap extends MapActivity {
	public static String Tag = "ArroundMap";

	SlidingDrawer sdUser;

	LinearLayout ly_Me;
	TextView tv_name, tv_distance;
	ImageView im_avatar, im_status;

	ListView lUser;
	MapView mMap;
	UserItemizedOverlay mUserOverlay;
	DtOverlay mOvlerlay;
	List<Overlay> mapOverlays;
	ArrayList<Her> arrayHer;
	ArrayList<AroundUser> arroundUser;

	static Toast t;
	Handler mHandler = new Handler();
	boolean cancel = false;

	@Override
	protected void onCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.arround);

		t = Toast.makeText(this, "", Toast.LENGTH_SHORT);

		sdUser = (SlidingDrawer) findViewById(R.id.sd_list_user);

		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_distance = (TextView) findViewById(R.id.tv_distance);
		im_avatar = (ImageView) findViewById(R.id.im_avatar);
		im_status = (ImageView) findViewById(R.id.im_status);
		ly_Me = (LinearLayout) findViewById(R.id.item_me);

		lUser = (ListView) findViewById(R.id.lst_map_user);
		mMap = (MapView) findViewById(R.id.map_view);
		mMap.setBuiltInZoomControls(true);

		mapOverlays = mMap.getOverlays();

		mOvlerlay = new DtOverlay(this, mMap);

		Drawable drawable = this.getResources()
				.getDrawable(R.drawable.noavatar);
		Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
		Drawable d = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, 50,
				50, true));
		mUserOverlay = new UserItemizedOverlay(d, this);

		mMap.getOverlays().add(mOvlerlay);
		mMap.postInvalidate();

		GeoPoint point2 = new GeoPoint(35410000, 139460000);
		OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa!",
				"I'm in Japan!");

		mOvlerlay.animatedTo(Function.getLastGeopoint(this));
		arrayHer = new ArrayList<Her>();
		addMe();

		mUserOverlay.addOverlay(overlayitem2);
		mapOverlays.add(mUserOverlay);
		try {
			// update position
			updatePosition();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		// get basic info
		getBasicInfo();

		// get list her
		getUserArround();

		// for test
		// init(15);

	}

	private void updatePosition() throws NullPointerException {
		Location l = Function.getLastGeopoint(this);
		Dating.ME._latitude = l.getLatitude() + "";
		Dating.ME._longitude = l.getLongitude() + "";
		if (!Dating.ME._latitude.equals("")
				&& !Dating.ME._longitude.equals("0")) {
			try {
				DatingService dating = new DatingService();
				dating.updateMyPosition(Float.parseFloat(Dating.ME._latitude),
						Float.parseFloat(Dating.ME._longitude));
				// showToast("update position success");
			} catch (Exception e) {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						showToast("update position failed");
					}
				});
			}
		}
	}

	private void getBasicInfo() {

	}

	private void addHerToMap(Her her) throws NumberFormatException,
			NullPointerException {
		Log.e("add to map her", her._latitude + " ");
		Log.e("add to map her", her._longitude + " ");

		Location _location = her.getLocation();
		int lat = (int) (_location.getLatitude() * 1E6);
		int lng = (int) (_location.getLongitude() * 1E6);

		GeoPoint _pointHer = new GeoPoint(lat, lng);
		OverlayItem overlayitem2 = new OverlayItem(_pointHer, her._fullname,
				her._address);
		mUserOverlay.addOverlay(overlayitem2);
	}

	private void getUserArround() {
		showDialog(Constant.DIALOG_LOADING);
		new Thread() {
			@Override
			public void run() {
				super.run();

				try {
					Location l = Function.getLastGeopoint(ArroundMap.this);

					if (l != null) {
						DatingService dt = new DatingService();
						try {
							arroundUser = dt.getSinglesAroundMe(l.getLatitude()
									+ "", l.getLongitude() + "",
									Pref.getDistance(ArroundMap.this),
									Pref.getOffset(ArroundMap.this),
									Pref.getLenght(ArroundMap.this));
							mHandler.post(new Runnable() {

								@Override
								public void run() {
									showToast("num around:"
											+ arroundUser.size() + "");
								}
							});
							if (arroundUser.size() > 0) {
								for (AroundUser _item : arroundUser) {
									final Her _her = getHerFromUser(_item);
									if (_her != null) {
										arrayHer.add(_her);
										mHandler.post(new Runnable() {

											@Override
											public void run() {
												addHerToMap(_her);
												MapUserAdapter adapter = new MapUserAdapter(
														ArroundMap.this, mMap,
														mOvlerlay, arrayHer);
												lUser.setAdapter(adapter);
											}
										});
									}
								}
								mHandler.post(new Runnable() {

									@Override
									public void run() {
										dismissDialog(Constant.DIALOG_LOADING);
									}
								});
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} catch (NullPointerException e) {
					e.printStackTrace();
				} finally {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							try {
								dismissDialog(Constant.DIALOG_LOADING);
							} catch (IllegalArgumentException e2) {
							}
						}
					});
				}

			}
		}.start();
	}

	private Her getHerFromUser(AroundUser user) {
		Her _her = new Her(0, "id0", "her name", "15-07-1990",
				"khacpv@gmail.com", "", "SYSTEM", "", "0", "0.0", "0.0", "",
				"", "Unkown: ", "MATCHING");
		_her._distance = user.getDistance(0);
		_her._id_username = user.getUserID(0) + "";
		Log.v("get user id from arround user", user.getUserID(0) + "");
		_her._latitude = user.getLatitude();
		_her._longitude = user.getLongitude();
		Log.e("her latitude", _her._latitude);
		Log.e("her longitude", _her._longitude);
		DatingService dt = new DatingService();
		try {
			BasicInformation _bsInfo = dt.getUserInfo(user.getUserID(0));
			_her._address = _bsInfo.getCurArea("");
			_her._distance = Double.parseDouble(_bsInfo.getDistance(0) + "");
			_her._email = _bsInfo.getEmail("");
			_her._gender = _bsInfo.getGender(0) + "";
			_her._id_username = _bsInfo.getId(0) + "";
			_her._lastLogin = _bsInfo.getLastLogin("");
			_her._fullname = _bsInfo.getName("");
			_her._status = _bsInfo.getOnline(false);
			_her._bmp = getAvatar(_her._id_username);
			showToast(_bsInfo.getEmail(""));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return _her;
	}

	private Bitmap getAvatar(String idUser) {
		DatingService dt = new DatingService();
		ArrayList<String> listAvatar;
		try {
			listAvatar = dt.getUserPhoto(Integer.parseInt(idUser), 0);
			Bitmap avatar = Function
					.getBitmapFromUrl(new URL(listAvatar.get(0)));
			return avatar;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	OnClickListener meClicked = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent infoMe = new Intent(ArroundMap.this, UserInfo.class);
			Bundle b = new Bundle();
			b.putInt("user_id", Integer.parseInt(Dating.ME._id_username));
			infoMe.putExtras(b);
			startActivity(infoMe);
		}
	};

	private void addMe() {
		Dating.ME = Me.getInstance(Dating.ME);
		tv_name.setText(Dating.ME._fullname);
		tv_distance.setVisibility(View.GONE);
		im_status.setVisibility(View.GONE);
		if (Dating.ME._bmp != null)
			im_avatar.setImageBitmap(Dating.ME._bmp);
		ly_Me.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Location l = Function.getLastGeopoint(ArroundMap.this);
				if (l != null) {
					Dating.ME._latitude = l.getLatitude() + "";
					Dating.ME._longitude = l.getLongitude() + "";
				}
				mOvlerlay.animatedTo(Dating.ME.getLocation());
				// sdUser.setPressed(false);
				showToast(Dating.ME._latitude + "-" + Dating.ME._longitude);
			}
		});
		tv_name.setOnClickListener(meClicked);
		tv_distance.setOnClickListener(meClicked);
	}

	@SuppressWarnings("unused")
	private void init(int num) {

		for (int _i = 1; _i < num; ++_i) {
			Her h = new Her(_i, "id0", "her name", "15-07-1990",
					"khacpv@gmail.com", "", "SYSTEM", "", "0",
					String.valueOf((_i + 555) % 100),
					String.valueOf((_i + 556) % 100), "", "", "Unkown: " + _i,
					"MATCHING");
			if (_i % 3 == 0)
				h.setOnline(true);
			arrayHer.add(h);
		}
		MapUserAdapter adapter = new MapUserAdapter(this, mMap, mOvlerlay,
				arrayHer);
		lUser.setAdapter(adapter);
	}

	@Override
	protected void onResume() {
		super.onResume();

		boolean enableCompass = mOvlerlay.enableCompass();
		boolean enableMyLocation = mOvlerlay.enableMyLocation();

		if (!enableCompass)
			Log.v(Tag, "can not enable compass");
		if (!enableMyLocation)
			Log.v(Tag, "can not enable MyLocation");
	}

	@Override
	protected void onPause() {
		super.onPause();
		mOvlerlay.disableCompass();
		mOvlerlay.disableMyLocation();
	}

	@Override
	protected boolean isRouteDisplayed() {

		return false;
	}

	// SUPER METHOD
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		Dialog d = new Dialog(this);
		d.setCancelable(true);
		// d.setCanceledOnTouchOutside(true);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.loading);
		switch (id) {
		case Constant.DIALOG_LOADING:
			d.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel = true;
				}
			});
			// d.setTitle("Loging in...");
			cancel = false;
			d.show();
			break;

		default:
			break;
		}
		return d;
	}

	public static void showToast(String text) {
		if (t != null) {
			t.cancel();
		}
		t.setText(text);
		t.show();
	}
}
